import { RepoLink } from '@brillout/docpress'
import { projectInfo } from '../../utils'

Instead of using relative import paths,
which can be cumbersome,
you can use path aliases:

```js
import { Counter } from '../../../../components/Counter' // [!code --]
import { Counter } from '#root/components/Counter' // [!code ++]
```

Where `#root/` denotes your project's root directory.

You may need to define your path aliases at up to three different places:
 - `vite.config.js#resolve.alias` (for files processed by Vite)
 - `package.json#imports` (for Node.js files that aren't processed by Vite)
 - `tsconfig.json#compilerOptions.paths` (for TypeScript)

Example:
 - <RepoLink path='/examples/path-aliases' />


## Vite

```js
// vite.config.js

export default {
  resolve: {
    alias: {
     "#root": __dirname,
    }
  }
}
```

> The Vite config `resolve.alias` only applies to files that are processed by Vite.
> Note that some of your server files may not be processed by Vite,
> see the [Node.js section below](#node-js).

We recommend following the [Node.js convention](https://nodejs.org/api/packages.html#subpath-imports:~:text=must%20always%20start%20with%20%23%20to%20ensure%20they%20are%20disambiguated%20from%20external%20package%20specifiers) to prefix path aliases with the special character `#`.

See also:
 - [Vite > `resolve.alias`](https://vitejs.dev/config/shared-options.html#resolve-alias)
 - <RepoLink path='/examples/path-aliases/vite.config.ts' />


## Node.js

```json
// package.json

{
  "imports": {
    // JavaScript:
    "#root/*": "./*.js",
    // TypeScript:
    "#root/*": "./*.ts"
  }
}
```

See also:
 - [NodeJS > Subpath imports](https://nodejs.org/api/packages.html#subpath-imports)
 - <RepoLink path='/examples/path-aliases/package.json' />

Vite's `vite.config.js#resolve.alias` only applies to files that are processed by Vite.
(In other words: the `+*.js` files and their imports.)

Browser files are always processed by Vite,
but this isn't always the case for Node.js server files,
for example <RepoLink path="/boilerplates/boilerplate-react/server/index.js" text="Express.js server code"/>.

You can use Node.js's built-in support `package.json#imports` or, alternatively, you can use one of many npm packages such as [`module-alias`](https://github.com/ilearnio/module-alias). (Example of using `module-alias`: [/examples/path-aliases (@c914dad)](https://github.com/vikejs/vike/tree/c914dade5f0809ff330478c3531928055abdadef/examples/path-aliases).)


## TypeScript

If you use TypeScript, then TypeScript needs to know about your path aliases.

```json
// tsconfig.json

{
  "compilerOptions": {
    "paths": {
      "#root/*": ["./*"]
    }
  }
}
```

See also:
 - [TypeScript > `tsconfig.json#compilerOptions.paths`](https://www.typescriptlang.org/tsconfig#paths)
 - <RepoLink path='/examples/path-aliases/tsconfig.json' />
